package com.alks.common.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author: chen
 * @date: 2024/12/7
 * @description:
 */
@Configuration
@Slf4j
public class RedissonConfig {


    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private  String port;

    @Value("${spring.redis.password}")
    private String password;


    private static String ADDRESS_PREFIX = "redis://";

    /**
     * 单机模式
     */
    @Bean
    public RedissonClient initBean() {
        // 单机模式
        if (StringUtils.isNotBlank(host)) {
            log.info("redis is single mode");
            return redissonSingle();
        }

        log.error("redisson config can not support this redis mode");
        return null;
    }

    /**
     * 单机模式
     */
    private RedissonClient redissonSingle() {
        Config config = new Config();
        String address = ADDRESS_PREFIX+host+":"+port;
        //设置
        config.setCodec(new StringCodec())
                //这是用的集群server
                .useSingleServer()
                .setAddress(address)
                .setTimeout(3000)
                .setRetryAttempts(5) // 重试次数
                .setRetryInterval(1500) // 重试间隔
                .setPingConnectionInterval(1000); // PING 心跳间隔
        if (StringUtils.isNotBlank(password)) {
            config.useSingleServer().setPassword(password);
        }
        return Redisson.create(config);
    }

}
